<?php
namespace Lmkj\Controller;
use Think\Controller;

class ContentController extends CommonController {
	public $category;

	public function __construct() {
		parent::__construct();
		$this -> category = D('Category');
	}

	/**
	 * 内容显示页面
	 */
	public function index() {
		
		$Article = M('Article'); // 实例化User对象
		// 进行分页数据查询 注意page方法的参数的前面部分是当前的页数使用 $_GET[p]获取
		$_GET['p'] = $_GET['p'] ? $_GET['p'] : 0;
		$list = $Article->order('addtime')->page($_GET['p'].',10')->select();
		$this->assign('list',$list);// 赋值数据集
		$count      = $Article->count();// 查询满足要求的总记录数
		
		
		$Page       = new \Think\Page($count,10);// 实例化分页类 传入总记录数和每页显示的记录数
		$s = $Page->setConfig('header','个会员');
		$show       = $Page->show();// 分页显示输出
		$this->assign('page',$show);// 赋值分页输出
		$this->display(); // 输出模板
	}


/********************************************************************栏目管理************************************************************/
	/**
	 * 显示分类管理
	 */
	public function categoryList() {
		$data = $this -> category -> getAllData();
		foreach ($data as $k => $v) {
			$data[$k]['cate_time'] = strtotime($v['cate_time']);
		}
		$Data = new \Think\Data();
		$data = $Data::tree($data, 'cate_title', 'category_id', 'cid');
		$this -> assign('data', $data);
		$this -> display();
	}

	/**
	 * 添加或编辑栏目
	 */
	public function editAddCate() {
		if (IS_POST) {
			$postData = I('post.', '', 'htmlspecialchars');
			if (isset($postData['id'])) {//编辑
				$data = $this -> category -> editData($postData['id']);
				if ($data) {
					$this -> success('修改成功', U('Lmkj/Content/categoryList'));
				} else {
					$this -> error('修改失败', U('Lmkj/Content/categoryList'));
				}

			} else {//添加
				$data = $this -> category -> addData();
				if ($data) {
					$this -> success('新增成功', U('Lmkj/Content/categoryList'));
				} else {
					$this -> error('新增失败', U('Lmkj/Content/categoryList'));
				}
			}
		}
	}

	/**
	 * 删除栏目
	 */
	public function delCate() {
		if (IS_AJAX) {
			$data = $this -> category -> delData();
			if ($data) {
				$this -> ajaxReturn(1);
			} else {
				$this -> ajaxReturn(0);
			}
		}
	}

	/**
	 * 显示添加内容
	 */
	public function showAddContent() {
		if (IS_GET) {
			$id = I('get.id', 0, 'intval');
			if ($id) {
				$this -> assign('id', $id);
				//获得当前的这个id下的数据
				$data = $this -> category -> getOneData($id);
				$this -> assign('data', $data);
			}
			$this -> display();
		}

	}

	/**
	 * 显示添加子栏目
	 */
	public function showAddSonContent() {
		if (IS_GET) {
			$id = I('get.id', 0, 'intval');
			if ($id) {
				$this -> assign('id', $id);
			}
			$this -> display();
		}
	}

	/**
	 * 添加子栏目
	 */
	public function addSonContent() {
		if (IS_POST) {
			$data = $this -> category -> addSonData();
			if ($data) {
				$this -> success('修改成功', U('Lmkj/Content/categoryList'));
			} else {
				$this -> error('修改失败', U('Lmkj/Content/categoryList'));
			}
		}
	}
	
	/********************************************************************栏目管理************************************************************/
	
	/********************************************************************文章管理************************************************************/
	
	/**
	 * 添加文章
	 */	
	public function showAddArticle(){
		//获得网站栏目
		$data = $this -> category -> getAllData();
		foreach ($data as $k => $v) {
			$data[$k]['cate_time'] = strtotime($v['cate_time']);
		}
		$Data = new \Think\Data();
		$data = $Data::tree($data, 'cate_title', 'category_id', 'cid');
		$this -> assign('data', $data);
		
		//获得属性
		$attr = M('Attr')->field('attr_id,attr_name')->select();
		$this->assign('attr',$attr);
		
		$this->display();
	}
	
	/**
	 * 添加文章
	 */
	public function addAritcle(){
		$postData = I('post.');
//		var_dump($postData);
		
		$str = $postData['content'];
		//处理摘要
		if(isset($postData['auto_desc'])){
			$newData['desc'] = mb_substr( $str, 0, (int)$postData['auto_desc_length'], "utf-8");
		}
		//处理缩略图
		if(isset($postData['auto_thumb'])){
			$preg = "/<\s*img\s+src\s*=\s*(\'|\")(.*?)\\1[^>]*\/?\s*>/is";
			$num = $postData['auto_thumb_num'];
			preg_match_all($preg, $str, $arr);
			$newData['thumb'] = $arr[2][$num];
		}else{
			$newData['thumb'] = $postData['thumb'];
		}
		//处理上传时间
		if($postData['addtime'] == ''){
			$newData['addtime'] = date('Y-m-d H:i:s',time());
		}else{
			$newData['addtime'] = $postData['addtime'];
		}
		
		$newData['title'] = $postData['title'];
		$newData['color'] = $postData['color'];
		$newData['new_window'] = isset($postData['new_window']) ? 1 : 0;
		$newData['cid'] = $postData['cid'];
		$newData['seo_title'] = $postData['seo_title'];
		$newData['tag'] = $postData['tag'];
		$newData['keywords'] = $postData['keywords'];
		$newData['description'] = $postData['description'];
		$newData['redirecturl'] = $postData['redirecturl'];
		$newData['arc_sort'] = $postData['arc_sort'];
		$newData['click'] = $postData['click'];
		
		$aid = M('Article')->data($newData)->add();
		
		if($aid){
			M('Article_data')->data(array('aid'=>$aid,'content'=>$postData['content']))->add();
			//处理属性	
			foreach($postData['attr'] as $v){
				$atardata = array('attr_id'=>$v,'article_id'=>$aid);
				M('Attr_article')->data($atardata)->add();
			}
			$this -> success('添加成功', U('Lmkj/Content/index'));
		}else{
			$this -> error('添加失败', U('Lmkj/Content/index'));
		}
	}
	
	
	/**
	 * 显示上传
	 */
	public function uploadFile(){
		$set = array();
		switch ($_GET['type']) {
            case 'thumb':
                //缩略图字段
                $set['type'] = 'thumb';
                $set['name'] = 'thumb';
                $set['allow_size'] = 2000;
                $set['num'] = 1;
                $set['filetype'] = '*.gif; *.jpg; *.png';
                break;
            case 'image':
                $set['type'] = 'image';
                $set['name'] = $_GET['name'];
                $set['allow_size'] *= 1000;
                $set['num'] = 1;
                $set['filetype'] = '*.gif; *.jpg; *.png';
                break;
            case 'images':
                $set['type'] = 'images';
                $set['name'] = $_GET['name'];
                $set['allow_size'] *= 1000;
                $set['filetype'] = '*.gif; *.jpg; *.png';
                break;
            case 'files':
                $set['type'] = 'files';
                $set['name'] = $_GET['name'];
                $set['allow_size'] *= 1000;
                $filetype = explode(',', $set['filetype']);
                $set['filetype'] = '';
                foreach ($filetype as $t) {
                    $set['filetype'] .= '*.' . $t . ';';
                }
                $set['filetype'] = substr($set['filetype'], 0, -1);
                break;
        }
		
		$this->assign('host',$_SERVER['HTTP_HOST']);
        $this->assign('set', $set);
		$this->display();
	}
	
	/**
	 * 上传文件
	 */
	public function upload(){
	    $upload = new \Think\Upload();// 实例化上传类
	    $upload->maxSize   =     3145728 ;// 设置附件上传大小
	    $upload->exts      =     array('jpg', 'gif', 'png', 'jpeg');// 设置附件上传类型
	    $upload->rootPath  = $_SERVER['DOCUMENT_ROOT'].'/Uploads/'; // 设置附件上传根目录
	    $upload->savePath =  ''; 
	    // 上传文件 
	    is_dir($upload->rootPath) || mkdir($upload->rootPath,0777,true);
	    $info  =  $upload->upload();

	    if(!$info) {// 上传错误提示错误信息
		   $this->ajaxReturn($upload->getError());	
	    }else{// 上传成功
	   	   M('Upload')->add($info['Filedata']);
	       $this->ajaxReturn($info['Filedata']);
	    }
	}
	/**
	 * 删除图片
	 */
	public function ajaxDelImg(){
		$postData = I('post.');
		//删除表里面的内容，并且删除这个目录下的这个文件
		$data = M('Upload')->field('savepath,savename')->where(array('size'=>$postData['filesize'],'name'=>$postData['filename']))->select();
		foreach($data as $v){
			$filename = $_SERVER['DOCUMENT_ROOT'].'/Uploads/'.$v['savepath'].$v['savename'];
			
			if(is_file($filename)) {
				@chmod($filename, 0777);
				@unlink($filename);
			}  
			
			M('Upload')->where(array('savename'=>$v['savename']))->delete();
		}
		$data = M('Upload')->field('savepath,savename')->where(array('size'=>$postData['filesize'],'name'=>$postData['filename']))->select();
		if(empty($data)){
			$this->ajaxReturn(1);
		}else{
			$this->ajaxReturn(0);
		}
	}
	
	/**
	 * 删除文章
	 */
	public function ajaxDelArticle(){
		if(IS_AJAX){
			$id = i('post.id');
			//先查询下有没有图片
			$article = M('Article')->where(array('aid'=>$id))->find();
			if($article['thumb'] == ""){
				$data = M('Article')->where(array('aid'=>$id))->delete();
				if($data ){
					$id = M('Article_data')->where(array('aid'=>$id))->delete();
					if($id){
						$this->ajaxReturn(1);
					}else{
						$this->ajaxReturn(0);
					}
					
				}else{
					$this->ajaxReturn(0);
				}
			}else{
				$img = $article['thumb'];
				$filename = $_SERVER['DOCUMENT_ROOT'].$img;
				if(is_file($filename)) {
					@chmod($filename, 0777);
					@unlink($filename);
				}  
				$data = M('Article')->where(array('aid'=>$id))->delete();
				if($data ){
					$id = M('Article_data')->where(array('aid'=>$id))->delete();
					if($id){
						$this->ajaxReturn(1);
					}else{
						$this->ajaxReturn(0);
					}
					
				}else{
					$this->ajaxReturn(0);
				}
			}
			
			
		}	
	}
	
	//批量删除
	public function ajaxDelAll(){
		if(IS_AJAX){
			$ids = I("post.ids");
			foreach($ids as $v){
				$article = M('Article')->where(array('aid'=>$v))->find();
				if($article['thumb'] == ""){
					M('Article')->where(array('aid'=>intval($v)))->delete(); //删文章
					M('Article_data')->where(array('aid'=>intval($v)))->delete(); //删文章详细
				}else{
					$img = $article['thumb'];
					$filename = $_SERVER['DOCUMENT_ROOT'].$img;
					if(is_file($filename)) {
						@chmod($filename, 0777);
						@unlink($filename);
					}  
				}
			}
			$this->ajaxReturn(1);
		}
	}
	
	
	/********************************************************************文章管理************************************************************/
	/**
	 * 显示链接管理
	 */
	public function showLinkManage() {
		$this -> display();
	}
	
	
	

}
?>